package com.jbh.wanandroidkotlin.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.afollestad.materialdialogs.GravityEnum
import com.afollestad.materialdialogs.MaterialDialog
import com.google.gson.Gson
import com.jbh.apilibrary.AppData
import com.jbh.apilibrary.bean.LoginResultBean
import com.jbh.apilibrary.i.ApiCallBack
import com.jbh.wanandroidkotlin.R
import com.jbh.wanandroidkotlin.manager.UserInfoManager
import com.jbh.wanandroidkotlin.util.closeInput
import kotlinx.android.synthetic.main.activity_logon.*

class LoginActivity : BaseActivity() , View.OnClickListener{


    /**
     * @param savedInstanceState
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_logon)
        btn_login.setOnClickListener(this)
        btn_register.setOnClickListener(this)

        if (UserInfoManager.newInstance().isLogin()){
            this@LoginActivity.startActivity(Intent(this@LoginActivity,MainActivity::class.java))
        }
    }



    /**
     *
     * 登录接口
     *
     */
    private fun loginTask(userName:String,userPwd:String){
        AppData.instance().loginTask(userName,userPwd,object : ApiCallBack<LoginResultBean> {
            override fun success(data: LoginResultBean) {
                runOnUiThread{
                    println("[loginTask] - >success = ${Gson().toJson(data)}")
                    UserInfoManager.newInstance().saveInfo(data)
                    this@LoginActivity.startActivity(Intent(this@LoginActivity,MainActivity::class.java))
                }
            }
            override fun error(error: String) {
                runOnUiThread{
                    println("[loginTask] ->error = $error")
                    Toast.makeText(this@LoginActivity,error,Toast.LENGTH_LONG).show()
                }
            }
        })
    }




    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.btn_login -> {
                closeInput(this)
                loginTask(username.text.toString().trim(),userPassword .text.toString().trim())
            }
            R.id.btn_register->{
                goToActivity(RegisterActivity::class.java)
            }
        }
    }



    fun showDialog(){
        MaterialDialog.Builder(this)
            .title("标题")
            .titleGravity(GravityEnum.CENTER)
            .content("内容")
            .positiveText("确认")
            .negativeText("取消")
            .show();
    }
}